#include "cadreposttab.h"
#include "ui_cadreposttab.h"
#include <QDialog>
#include <QGridLayout>
#include <QLineEdit>
#include <QSqlQuery>
#include <QPushButton>
#include <QSqlTableModel>
#include "timeeditdelegate.h"
#include <QDebug>
#include <QLabel>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRelationalDelegate>
#include <QSqlRelationalTableModel>
#include "cdateedit.h"
#include "cadreutil.h"

CadrePostTab::CadrePostTab(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CadrePostTab)
{
    ui->setupUi(this);

    qulifytypeHash.insert("0",QString::fromUtf8("现任"));
    qulifytypeHash.insert("1",QString::fromUtf8("拟任"));
    qulifytypeHash.insert("2",QString::fromUtf8("拟免"));
}

CadrePostTab::~CadrePostTab()
{
    delete ui;
}

void CadrePostTab::initPostTableView(QString curPerson)
{
    postModel = new QSqlRelationalTableModel(this);
    postModel->setTable("Post");
    postModel->setRelation(2, QSqlRelation("RankCode", "RankID", "RankName"));
    postModel->setRelation(3, QSqlRelation("PostCategoryCode", "PostCategoryID", "PostCategory"));
    postModel->setJoinMode(QSqlRelationalTableModel::LeftJoin);
    postModel->setEditStrategy(QSqlTableModel::OnFieldChange);// OnRowChange OnFieldChange OnManualSubmit
    QString filter = QString::fromUtf8("IDNum='%1' and QualifyType='0'").arg(curPerson);
    currentPerson=curPerson;
    postModel->setFilter(filter);
    postModel->select();
    postModel->setHeaderData(1, Qt::Horizontal, QString::fromUtf8("职务名称"));
    postModel->setHeaderData(2, Qt::Horizontal, QString::fromUtf8("职务级别"));
    postModel->setHeaderData(3, Qt::Horizontal, QString::fromUtf8("职务属性"));
    postModel->setHeaderData(6, Qt::Horizontal, QString::fromUtf8("任职性质"));
    postModel->setHeaderData(7, Qt::Horizontal, QString::fromUtf8("任职时间"));
    postModel->setHeaderData(8, Qt::Horizontal, QString::fromUtf8("任免文号"));
    ui->postTableView->horizontalHeader()->setVisible(true); //UI界面设置，总是恢复为false
    ui->postTableView->setModel(postModel);
    ui->postTableView->setItemDelegate(new QSqlRelationalDelegate(ui->postTableView));
    TimeEditDelegate *posttime = new TimeEditDelegate();
    ui->postTableView->setItemDelegateForColumn(7,posttime);
    ui->postTableView->setColumnHidden(0,true); // PostID
    ui->postTableView->setColumnHidden(4,true); // Explain
    ui->postTableView->setColumnHidden(5,true); // QualifyType
    ui->postTableView->setColumnHidden(9,true); // IDNum
    ui->postTableView->setColumnWidth(1,150);
    ui->postTableView->setColumnWidth(2,150);
    ui->postTableView->setColumnWidth(3,150);
    ui->postTableView->setColumnWidth(6,150);
    ui->postTableView->setColumnWidth(7,150);
    ui->postTableView->setColumnWidth(8,150);
    int i = postModel->rowCount()-1;
    ui->postTableView->selectRow(i);
    on_postTableView_clicked(postModel->index(i,0));


}
void CadrePostTab::setButtonEnable(bool i)
{
    ui->postAddButton->setEnabled(i);
    ui->postDeleteButton->setEnabled(i);
    ui->postDownButton->setEnabled(i);
    ui->postUpButton->setEnabled(i);
    if(i){
        ui->postTableView->setEditTriggers(QAbstractItemView::DoubleClicked);
        ui->postNameLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->postPropertyLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->postNumerLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->explainTextEdit->setFocusPolicy(Qt::StrongFocus);

    }else{
        ui->postTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->postNameLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->postPropertyLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->postNumerLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->explainTextEdit->setFocusPolicy(Qt::NoFocus);
    }
    ui->rankComboBox->setEnabled(i);
    ui->postCategoryComboBox->setEnabled(i);
    ui->postTimeDateEdit->setReadOnly(!i);
    ui->savePushButton->setEnabled(i);

}

void CadrePostTab::on_postAddButton_clicked()
{
    QDialog *addDialog = new QDialog(this);
    addDialog->setWindowTitle(trUtf8("添加职务"));
    addDialog->setGeometry(700,300,900,400);
    addDialog->setContentsMargins(10,0,10,0);
    QGridLayout *gridLayout = new QGridLayout(addDialog);
    gridLayout->setMargin(10);
    QLabel *nameLabel =new QLabel(trUtf8("职务名称"),addDialog);
    QLabel *rankLabel=new QLabel(trUtf8("职务级别"),addDialog);
    QLabel *postcategoryLabel=new QLabel(trUtf8("职务属性"),addDialog);
    QLabel *explainLabel=new QLabel(trUtf8("职务说明"),addDialog);
    QLabel *propertyLabel=new QLabel(trUtf8("任职性质"),addDialog);
    QLabel *posttimeLabel=new QLabel(trUtf8("任职时间"),addDialog);
    QLabel *postnumLabel=new QLabel(trUtf8("任免文号"),addDialog);
    QLineEdit *name = new QLineEdit(addDialog);
    CDateEdit *posttime = new CDateEdit(addDialog);
    posttime->setNullable(true);
    posttime->setDisplayFormat("yyyy-MM-dd");
    posttime->setCalendarPopup(true);
    posttime->setDate(QDate());
    QComboBox *rank = new QComboBox(addDialog);
    rhash = CadreUtil::initComboBox(rank,"","RankCode","RankID","RankName");
    QComboBox *postcategory = new QComboBox(addDialog);
    phash = CadreUtil::initComboBox(postcategory,"","PostCategoryCode","PostCategoryID","PostCategory");
    QTextEdit *explain = new QTextEdit(addDialog);
    QLineEdit *property = new QLineEdit(addDialog);
    QLineEdit *postnum = new QLineEdit(addDialog);
    gridLayout->addWidget(nameLabel,0,0);
    gridLayout->addWidget(name,0,1);
    gridLayout->addWidget(rankLabel,0,2);
    gridLayout->addWidget(rank,0,3);
    gridLayout->addWidget(postcategoryLabel,1,0);
    gridLayout->addWidget(postcategory,1,1);
    gridLayout->addWidget(propertyLabel,1,2);
    gridLayout->addWidget(property,1,3);
    gridLayout->addWidget(posttimeLabel,2,0);
    gridLayout->addWidget(posttime,2,1);
    gridLayout->addWidget(postnumLabel,2,2);
    gridLayout->addWidget(postnum,2,3);
    gridLayout->addWidget(explainLabel,3,0);
    gridLayout->addWidget(explain,3,1,1,2);
    explain->setMaximumHeight(60);

    QPushButton *yesButton = new QPushButton(trUtf8("确定"));
    QPushButton *cancelButton = new QPushButton(trUtf8("取消"));

    QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal);
    buttonBox->addButton(yesButton, QDialogButtonBox::AcceptRole);
    buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);

    gridLayout->addWidget(buttonBox,5,1,1,4,Qt::AlignHCenter);

    connect(buttonBox, SIGNAL(accepted()), addDialog, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), addDialog, SLOT(reject()));

    if(addDialog->exec()==QDialog::Accepted){
        QSqlQuery query;

        query.prepare("insert into Post (`PostName`, `RankID`, `PostCategory`, `Explain`,"
                      " `QualifyType`,`PostProperty`, `PostTime`, `PostNumber`, `IDNum`)"
                      " values(:name, :rank, :postcategory, :explain, :qualifytype, "
                      ":property, :posttime, :postnum, :idnum )");
        query.bindValue(":name",name->text());
        query.bindValue(":rank",rhash.key(rank->currentText()));
        query.bindValue(":postcategory",phash.key(postcategory->currentText()));
        query.bindValue(":explain",explain->toPlainText());
        query.bindValue(":qualifytype","0"); //现任
        query.bindValue(":property",property->text());
        query.bindValue(":posttime",posttime->date());
        query.bindValue(":postnum",postnum->text());
        query.bindValue(":idnum",currentPerson);
        if(query.exec()){
            QMessageBox::information(this,trUtf8("提示"),
               trUtf8("插入数据成功"),QMessageBox::Yes);
            initPostTableView(currentPerson);
        }else{
            QString info = query.lastError().databaseText();
            QMessageBox::information(this,trUtf8("插入数据库错误"),
               info,QMessageBox::Yes);
        }
    }
}


QSqlTableModel* CadrePostTab::getOriginalModel()
{
    QSqlTableModel *originalPostModel = new QSqlTableModel(this);
    originalPostModel->setTable("Post");
    QString filter = QString::fromUtf8("IDNum='%1'and QualifyType='0'").arg(currentPerson);
    originalPostModel->setFilter(filter);
    originalPostModel->select();
    originalPostModel->setEditStrategy(QSqlTableModel::OnFieldChange);
    return originalPostModel;
}

void CadrePostTab::on_postDeleteButton_clicked()
{
    CadreUtil::deleteRow(postModel, ui->postTableView);
}

void CadrePostTab::on_postUpButton_clicked()
{
    QSqlTableModel *originalPostModel = getOriginalModel();
    int cur =CadreUtil::moveUpOne(originalPostModel,0,ui->postTableView);
    initPostTableView(currentPerson);
    ui->postTableView->selectRow(cur);
}

void CadrePostTab::on_postDownButton_clicked()
{
    QSqlTableModel *originalPostModel = getOriginalModel();
    int cur = CadreUtil::moveDownOne(originalPostModel,0,ui->postTableView);
    initPostTableView(currentPerson);
    ui->postTableView->selectRow(cur);
}

void CadrePostTab::on_postTableView_clicked(const QModelIndex &index)
{
    QSqlRecord record = postModel->record(index.row());
    postid = record.value("PostId").toString();
    QSqlQuery query = postModel->query();
    QString sql = QString::fromUtf8("SELECT `PostName`, `RankID`, `PostCategory`, "
                  "`Explain`, `QualifyType`, `PostProperty`, `PostTime`, "
                  "`PostNumber`, `IDNum` FROM Post where PostID = '%1';"
                   ).arg(postid);
    query.exec(sql);
    query.next();
    QSqlRecord rowData = query.record();
    ui->postNameLineEdit->setText(rowData.value("PostName").toString());
    QString rankID= rowData.value("RankID").toString();
    rhash =CadreUtil::initComboBox(ui->rankComboBox,rankID,"RankCode","RankID","RankName");
    QString postcategory= rowData.value("PostCategory").toString();
    phash =CadreUtil::initComboBox(ui->postCategoryComboBox,postcategory,"PostCategoryCode","PostCategoryID","PostCategory");
    ui->postPropertyLineEdit->setText(rowData.value("PostProperty").toString());
    ui->postTimeDateEdit->setNullable(true);
    ui->postTimeDateEdit->setDate(rowData.value("PostTime").toDate());
    ui->postNumerLineEdit->setText(rowData.value("PostNumber").toString());
    ui->explainTextEdit->setPlainText(rowData.value("Explain").toString());
}

void CadrePostTab::on_savePushButton_clicked()
{

    QSqlQuery query;

    query.prepare(" UPDATE Post SET `PostName`= :name , `RankID`= :rank ,"
                  " `PostCategory`= :postcategory, `Explain`= :explain , `QualifyType`= :qualifytype,"
                  " `PostProperty`= :property , `PostTime`= :posttime, `PostNumber`= :postnum,"
                  " `IDNum`= :idnum"
                  " WHERE `PostID`= :postid");
    query.bindValue(":name",ui->postNameLineEdit->text());
    query.bindValue(":rank",rhash.key(ui->rankComboBox->currentText()));
    query.bindValue(":postcategory",phash.key(ui->postCategoryComboBox->currentText()));
    query.bindValue(":explain", ui->explainTextEdit->toPlainText());
    query.bindValue(":qualifytype","0"); //现任
    query.bindValue(":property",ui->postPropertyLineEdit->text());
    query.bindValue(":posttime",ui->postTimeDateEdit->date());
    query.bindValue(":postnum",ui->postNumerLineEdit->text());
    query.bindValue(":idnum",currentPerson);
    query.bindValue(":postid",postid);
    if(query.exec()){
        QMessageBox::information(this,trUtf8("提示"),
           trUtf8("数据更新成功"),QMessageBox::Yes);
        initPostTableView(currentPerson);
    }else{
        QString info = query.lastError().databaseText();
        QMessageBox::information(this,trUtf8("更新数据错误"),
           info,QMessageBox::Yes);
    }
}
